<?php
class Admin_Model_Ventes extends Zend_Db_Table_Abstract
{
    protected $_name = 'ventes';
	protected $_primary  = 'p_ventes';

	public function getListVentes()
	{
		$sql = $this->getAdapter()->select()
		->from($this->_name)
		->where('deleted = 0')
		->order('dtvente desc');

		return $this->getAdapter()->fetchAll($sql);
	}
	
	public function getVentes($id)
	{
		$sql = $this->getAdapter()->select()
		->from($this->_name)
		->where('p_ventes = ?', $id);
		
		return $this->getAdapter()->fetchRow($sql);
	}
	
	public function getHoraires($id)
	{
		$sql = "SELECT max(c.p_categories) category_id, max(c.nom) description,
		min(num_article) min_art_num, max(num_article) max_art_num
		from categories c,articles a
		where c.p_categories=a.f_categories
		and a.f_ventes = $id
		and c.f_ventes = $id
		group by c.p_categories
		order by a.num_article";
	
		return $this->getAdapter()->fetchAll($sql);
	}

	public function removeVentes($id)
	{
		$this->getAdapter()->delete($this->_name, "p_ventes =" . $id);
		return true;
	}
	
	public function getVentesWithType($type_vente)
	{
	    $sql = "SELECT p_ventes FROM ventes WHERE dtdeleted = '1900-01-01' AND type_vente = '$type_vente' AND dtvente <= NOW() ORDER BY dtvente DESC LIMIT 1";
	    return $this->getAdapter()->fetchRow($sql);
	}
	
	public function getVentesByDtdeleted()
	{
	    $sql = "SELECT p_ventes,dtvente,titre FROM ventes WHERE dtdeleted = '1900-01-01' ORDER BY dtvente desc";
	    return $this->getAdapter()->fetchAll($sql);
	}
	
    public function getClients()
	{
	    $sql = "SELECT p_clients,commission FROM clients where deleted = 0";
	    return $this->getAdapter()->fetchAll($sql);
	}
	
	public function getClientsVentes($f_ventes, $f_clients)
	{
	    $sql = "SELECT commission,num_client FROM clients_ventes where f_ventes = ". $f_ventes ." and f_clients = ". $f_clients;
	    return $this->getAdapter()->fetchRow($sql);
	}
	
    public function insertClientsVentes($p_clients, $new_vente, $numCli, $der)
	{
	    $sql = "INSERT INTO clients_ventes (f_clients,f_ventes,num_client,commission) VALUES ($p_clients, $new_vente, '$numCli', $der)";
	    return $this->getAdapter()->query($sql);
	}
	
	public function getCategories($f_ventes)
	{
	    $sql = "SELECT p_categories, nom, ordre, tva FROM categories WHERE deleted = 0 and f_ventes = " . $f_ventes;
	    return $this->getAdapter()->query($sql);
	}
	
    public function insertCategory($nom, $ordre, $tva, $new_vente)
	{
	    $sql = "INSERT INTO categories (nom,ordre,deleted,tva,f_ventes) values ('". $nom ."', $ordre,0, $tva, $new_vente)";
	    return $this->getAdapter()->query($sql);
	}

}